package com.situ.vivamarket.api.sys;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.situ.vivamarket.model.Brand;
import com.situ.vivamarket.model.search.BrandSearchBean;
import com.situ.vivamarket.service.BrandService;
import com.situ.vivamarket.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/api/v1/brand")
public class BrandApi {
  private BrandService brandService;
  @Autowired
  public void setBrandService(BrandService brandService) {
    this.brandService = brandService;
  }

  @GetMapping
    public ResponseEntity<JsonResult> list(BrandSearchBean bsb,
                                      @RequestParam (defaultValue = "1") Integer page,
                                      @RequestParam (defaultValue = "5") Integer limit)
  {
      Page<?> p =new Page<>(page,limit);
      List<Brand> brands=brandService.getAllBrands(bsb,p);
      PageInfo<Brand> pi=new PageInfo<>(brands);
      JsonResult result=JsonResult.successData(brands);
      result.setCount((int) pi.getTotal());
      return ResponseEntity.ok(result);
  }
    @GetMapping("/all")
    public ResponseEntity<JsonResult> list()
    {
        List<Brand> brands=brandService.getAllBrands(null,null);
        JsonResult result=JsonResult.successData(brands);
        return ResponseEntity.ok(result);
    }

  @DeleteMapping
    public ResponseEntity<JsonResult> delete(Integer[] ids){
      if(ids.length==0){
          return ResponseEntity.noContent().build();
      }else{
          int count=brandService.deleteByIds(ids);
          if(count>0){
              return ResponseEntity.ok(JsonResult.successData(count));
          }else{
              return ResponseEntity.ok(JsonResult.fail("删除品牌失败"));
          }
      }

  }
  @PostMapping
    public ResponseEntity<JsonResult> add(@Validated Brand brand){
      boolean success=brandService.add(brand);
      if(success){
          return ResponseEntity.ok(JsonResult.successData(brand));
      }else{
          return ResponseEntity.internalServerError().body(JsonResult.fail("新增品牌异常"));
      }
  }
  @PutMapping
    public ResponseEntity<JsonResult> update(@Validated Brand brand){
      boolean success=brandService.update(brand);
      if(success){
          return ResponseEntity.ok(JsonResult.successData(brand));
      }else{
          return ResponseEntity.internalServerError().body(JsonResult.fail("修改品牌异常"));
      }
  }
}
